import { login, logout, getInfo } from '@/api/account'
import { getToken, setToken, removeToken, getTokenExpires, setTokenExpires, removeTokenExpires } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const user = {
  state: {
    token: getToken(),
    expires: getTokenExpires(),
    name: '',
    avatar: '',
    user: {},
    roles: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_TOKEN_EXPIRES: (state, expires) => {
      let time = expires
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if (typeof (time) === 'string') {
          time = new Date(time.replace(/-/g, '/'))
        }
        if (typeof (time) === 'number' && ('' + time).length === 10) {
          time = parseInt(time) * 1000
        }
        date = new Date(time)
      }
      state.expires = date.getTime()
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data
          setToken(data.token)
          setTokenExpires(data.expires)
          commit('SET_TOKEN', data.token)
          commit('SET_TOKEN_EXPIRES', data.expires)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state, dispatch }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const data = response.data
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          commit('SET_NAME', data.name)
          commit('SET_USER', data)
          commit('SET_AVATAR', data.avatar)

          resetRouter()
          dispatch('permission/generateRoutes', 'admin').then((accessRoutes) => {
            router.addRoutes(accessRoutes)
            console.log(router)
            resolve(response)
          })
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          removeToken()
          resetRouter()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
